package com.winit.common.zook;

import org.apache.zookeeper.*;
import org.springframework.core.io.support.PropertiesLoaderUtils;

import java.io.*;
import java.util.*;

/**
 * Created by wanglin on 2018/5/3.
 */
public class ZookUtil {
    private static String zookUrl;
    static {
        try {
            Properties properties = PropertiesLoaderUtils.loadAllProperties("application.properties");
            zookUrl = properties.getProperty("zookUrl");
        } catch (Exception e) {
        }

    }
    public static List<String> getZookInfo() throws Exception {
        Watcher watcher = new Watcher() {
            @Override
            public void process(WatchedEvent event) {
            }
        };
        ZooKeeper zookeeper = new ZooKeeper(zookUrl, 5000, watcher);
        List<String> InfoList = zookeeper.getChildren("/dubbo", watcher);
        List<String> list = getServiceInfo(InfoList);
        return list;
    }

    private static List<String> getServiceInfo(List<String> zookInfoList) throws KeeperException, InterruptedException, IOException {
        Watcher watcher = new Watcher() {
            @Override
            public void process(WatchedEvent event) {
            }
        };
        ZooKeeper zookeeper = new ZooKeeper(zookUrl, 5000, watcher);
        List<String> list = new ArrayList<String>();
        for (String path : zookInfoList) {
            List<String> providers = zookeeper.getChildren("/dubbo/" + path + "/providers", watcher);
            if(providers.size()>0){
                list.add(providers.get(0));
            }
        }
        return list;
    }

}
